#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
直播流模型
"""

from sqlalchemy import Column, Integer, String, Enum, Text, DateTime, Boolean
import json
import enum
from sqlalchemy.sql import func
from app.core.database import Base

class StreamStatus(enum.Enum):
    """流状态枚举"""
    ACTIVE = "active"
    INACTIVE = "inactive"
    ERROR = "error"

class Stream(Base):
    __tablename__ = "streams"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False, comment="流名称")
    url = Column(String(500), nullable=False, comment="流地址")
    stream_type = Column(String(20), default="rtsp", comment="流类型")
    status = Column(Enum(StreamStatus, values_callable=lambda x: [e.value for e in x]), default=StreamStatus.INACTIVE, comment="状态")
    
    # 流配置
    resolution = Column(String(20), nullable=True, comment="分辨率")
    bitrate = Column(Integer, nullable=True, comment="码率(kbps)")
    fps = Column(Integer, nullable=True, comment="帧率")
    
    # 编解码器信息
    video_codec = Column(String(50), nullable=True, comment="视频编解码器")
    audio_codec = Column(String(50), nullable=True, comment="音频编解码器")
    
    # 用户信息
    act_uid = Column(Integer, nullable=False, comment="创建用户ID")
    
    # 描述信息
    description = Column(Text, default="", comment="直播流描述")
    
    # 状态信息
    is_recording = Column(Integer, default=0, comment="录制任务数量（0或1）")
    is_transcode = Column(Integer, default=0, comment="转码任务数量（可累加）")
    is_pushing = Column(Integer, default=0, comment="转推任务数量（可累加）")
    inuse = Column(Integer, default=1, comment="是否在使用中 1-使用中 0-已删除")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    last_check = Column(DateTime(timezone=True), nullable=True, comment="最后检查时间")
    
    def __repr__(self):
        return f"<Stream(id={self.id}, name={self.name}, type={self.stream_type})>"
    
    def to_dict(self):
        return {
            "id": self.id,
            "name": self.name,
            "url": self.url,
            "stream_type": self.stream_type,
            "status": self.status.value,
            "resolution": self.resolution,
            "bitrate": self.bitrate,
            "fps": self.fps,
            "video_codec": self.video_codec,
            "audio_codec": self.audio_codec,
            "act_uid": self.act_uid,
            "description": self.description,
            "is_recording": self.is_recording,
            "is_transcode": self.is_transcode,
            "is_pushing": self.is_pushing,
            "inuse": self.inuse,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "last_check": self.last_check.isoformat() if self.last_check else None
        }